<?php
	class Admin extends CI_Controller {
	   
       function __construct() {
	       parent::__construct();
           $user = $this->session->userdata('user');
           if (!$user) redirect('main/alogin');
           $this->load->model('users/users_db','Users');
           $this->load->model('Dataset_db');
	   }
       
       function adduser() {
            if( !$this->Dataset_db->check_access($this->router->class,$this->router->method)){
               echo "You do not have permission to view this page"; exit; 
            }
            //print_object($_POST); exit;
            $data = array();
            if($_POST['btnAddUser']) {
                //print_object($_POST); exit;
                $pdata = array();
                $fields = array(
						"name"
                        ,"roleid"
						,"username"
						,"disabled"
                        ,"mobile"
                        ,"email"
                        ,"address"				
						);
                foreach ($fields as $field) {
    				if (isset($_POST[$field])) $pdata[$field] = $this->input->post($field, true);
    			}
                
                $this->form_validation->set_rules('name', 'Name', 'trim|required|min_length[3]|max_length[100]|xss_clean');
                $this->form_validation->set_rules('roleid', 'Account Type', 'trim|required|integer|xss_clean');
                $this->form_validation->set_rules('username', 'User Name', 'trim|required|min_length[3]|max_length[20]|xss_clean');
                $this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[6]|max_length[20]|matches[cpassword]');
                $this->form_validation->set_rules('cpassword', 'Confirm Password', 'trim|required|min_length[6]|max_length[20]');
                $this->form_validation->set_rules('mobile', 'Mobile', 'trim|required|min_length[5]|max_length[15]|xss_clean');
                $this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email|min_length[5]|max_length[50]|xss_clean');
                $this->form_validation->set_rules('address', 'Address', 'trim|max_length[200]|xss_clean');
                $this->form_validation->run();
                $data["errors"] = $this->form_validation->error_array();

                
                if(!$this->Users->is_username_unique($this->input->post("username",true))) {
                    if(is_array($data['errors']))
                        array_push($data["errors"],"Username already taken. Choose a different one.");
                    else
                        $data["errors"] = array("Username already taken. Choose a different one.");
                }
                
                $data["postdata"] = $pdata;
                   
                if (count($data["errors"])>0) {
                    
                } else {
                    $pdata["password"] = md5($this->input->post("password",true));
                    $user = $this->session->userdata('user');
                    $pdata["createdby"] = $user['userid'];
                    $pdata['createdon'] = unix_to_human(now(), true);
                    //print_object($pdata); exit;
                    
                    $save_result = $this->Users->save_user($pdata);
                    if($save_result['result'] == 'S') {
                        $data["successes"] = array('User added successfully.');
                        $data["postdata"] = "";
                    } else {
                        $data["errors"] = array($save_result['error_message']);   
                    }   
                }
            }
                                    
            $navResult = $this->Dataset_db->buildNav();
            $data['rolelist'] = $this->Users->get_roles();
            $data['clabel'] = $navResult['selected']['group'];            
            $data['mlabel'] = $navResult['selected']['item'];
            $this->load->view('admin/adduser',$data);
       }
       
       function viewusers() {
            if( !$this->Dataset_db->check_access($this->router->class,$this->router->method)){
            echo "You do not have permission to view this page"; exit; }
            $data['ptitle'] = "User List";
            
            $filterdata = array(
                'items' => array(
                    array(
                        'label' => 'User Name',
                        'table' => 'usr',
                        'name' => 'username',
                        'value' => isset( $_POST["username"] ) ? $_POST["username"] : '',
                        'type' => 'text',
                        'data' => ''
                    ),
                    array(
                        'label' => 'Role',
                        'table' => 'usr',
                        'name' => 'roleid',
                        'value' => isset( $_POST["roleid"] ) ? $_POST["roleid"] : '',
                        'type' => 'select',
                        'data' => $this->Users->get_role_list(true)
                    ),
                    array(
                        'label' => 'Mobile',
                        'table' => 'usr',
                        'name' => 'mobile',
                        'value' => isset( $_POST["mobile"] ) ? $_POST["mobile"] : '',
                        'type' => 'text',
                        'data' => ''
                    ),
                    array(
                        'label' => 'Email',
                        'table' => 'usr',
                        'name' => 'email',
                        'value' => isset( $_POST["email"] ) ? $_POST["email"] : '',
                        'type' => 'text',
                        'data' => ''
                    )
                ),
                'action' => '/admin/viewusers',
                'submit' => 'btnSearchUser'
            );
            
            
            $data['dgdata'] = $this->Users->build_user_dg_data($filterdata);
            
            $data['filterdata'] = $filterdata;
               
            //print_object($data);exit;
            $navResult = $this->Dataset_db->buildNav();
            $data['navs'] = $navResult['links'];
            $data['clabel'] = $navResult['selected']['group'];            
            $data['mlabel'] = $navResult['selected']['item'];
            //print_object($data); exit;
            $this->load->view('searchitem',$data);
       }
       
       function viewuser( $itemid="" ) {
            if( !$this->Dataset_db->check_access($this->router->class,$this->router->method)){
            echo "You do not have permission to view this page"; exit; }
            if($itemid!="") {
                $itemid = xss_clean($itemid);
                $mi_result = $this->Users->get_user(array('userid'=> $itemid));
                if(count($mi_result) == 0) {
                    $data['errors'] = "Could not find the selected user";
                } else {
                    $data['userid'] = $mi_result[0]['userid'];
                    $data['username'] = $mi_result[0]['username'];
                    $data['roleid'] = $mi_result[0]['roleid'];
                    $data['disabled'] = $mi_result[0]['disabled'];
                    $data['name'] = $mi_result[0]['name'];
                    $data['mobile'] = $mi_result[0]['mobile'];
                    $data['email'] = $mi_result[0]['email'];
                    $data['address'] = $mi_result[0]['address'];
                    $data['roletitle'] = $mi_result[0]['roletitle'];
                }
                //$data['rolelist'] = $this->Users->get_roles();
                
                $navResult = $this->Dataset_db->buildNav();
                $data['navs'] = $navResult['links'];
                $data['clabel'] = $navResult['selected']['group'];            
                $data['mlabel'] = $navResult['selected']['item'];
                //print_object($data); exit;
                $this->load->view('viewuser',$data);
            } else {
                $data['error_message'] = "Could not find the selected user";
                $this->load->view('error_others',$data);
            }
       }
       
       function edituser() {
            if( !$this->Dataset_db->check_access($this->router->class,$this->router->method)){
               echo "You do not have permission to view this page"; exit; 
            }
            
            $data = array();
            $data['ptitle'] = "Edit User";
            if($_POST['btnUpdateUser']) {
                //print_object($_POST); exit;
                $pdata = array();
                $fields = array(
						"name"
                        ,"roleid"
						,"disabled"
                        ,"mobile"
                        ,"email"
                        ,"address"				
						);
                foreach ($fields as $field) {
    				if (isset($_POST[$field])) $pdata[$field] = $this->input->post($field, true);
    			}
                
                $this->form_validation->set_rules('name', 'Name', 'trim|required|min_length[3]|max_length[100]|xss_clean');
                $this->form_validation->set_rules('roleid', 'Account Type', 'trim|required|integer|xss_clean');
                $this->form_validation->set_rules('mobile', 'Mobile', 'trim|required|min_length[5]|max_length[15]|xss_clean');
                $this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email|min_length[5]|max_length[50]|xss_clean');
                $this->form_validation->set_rules('address', 'Address', 'trim|max_length[200]|xss_clean');
                $this->form_validation->run();
                $data["errors"] = $this->form_validation->error_array();
                
                $data["postdata"] = $pdata;
                   
                if (count($data["errors"])>0) {
                    
                } else {
                    
                    $save_result = $this->Users->save_user($pdata,$this->input->post('userid',true));
                    if($save_result['result'] == 'S') {
                        $data["successes"] = array('User updated successfully.');
                        $data["postdata"] = "";
                    } else {
                        $data["errors"] = array($save_result['error_message']);   
                    }   
                }
            }
            
            if( isset( $_POST["userid"] ) ) {
                $itemid = xss_clean($itemid);
                $mi_result = $this->Users->get_user(array('userid'=> $this->input->post("userid",true)));
                if(count($mi_result) == 0) {
                    $data['errors'] = "Could not find the selected user";
                } else {
                    $data['userid'] = $mi_result[0]['userid'];
                    $data['username'] = $mi_result[0]['username'];
                    $data['roleid'] = $mi_result[0]['roleid'];
                    $data['disabled'] = $mi_result[0]['disabled'];
                    $data['name'] = $mi_result[0]['name'];
                    $data['mobile'] = $mi_result[0]['mobile'];
                    $data['email'] = $mi_result[0]['email'];
                    $data['address'] = $mi_result[0]['address'];
                    $data['roletitle'] = $mi_result[0]['roletitle'];
                }
            }
            
            //print_object($data); exit;
                                    
            $navResult = $this->Dataset_db->buildNav();
            $data['rolelist'] = $this->Users->get_roles();
            $data['clabel'] = $navResult['selected']['group'];            
            $data['mlabel'] = $navResult['selected']['item'];
            $this->load->view('admin/edituser',$data);
       }
       
       function deleteuser() {
            if( !$this->Dataset_db->check_access($this->router->class,$this->router->method)){
            echo "You do not have permission to view this page"; exit; }
            $isJSON = isset($_GET['json']) ? $_GET['json'] : 0;
            $id = xss_clean($_GET['id']);
            //print_object($_POST);exit;
            $data['ptitle'] = "Delete User";
            if( isset( $id ) ) {
                $result = $this->Users->delete_user(array('userid'=> $id));
                //print_object($mg_result);exit;
                if(!$result) {
                    $data["status"] = 0;
                    $data["error"] = "User not found.";
                } else {
                    $data["status"] = 1;
                }
            } else {
                $data["status"] = 0;
                $data["error"] = "Invalid User.";
            }
            
            if($isJSON==1) {
                echo json_encode($data);
            }
       }
              
	}

/* End of file */